# coding:utf-8
'''
Created on 2010-1-4

@author: Jason Green
@author-email: guileen@gmail.com
'''
from djangosnippets.utils.asciizip import ascii_crypt, ascii_decrypt
import SocketServer

_key_dict = {}
counter= 0
class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "%s wrote:" % self.client_address[0]
        print self.data
        # just send back the same data, but upper-cased
        self.request.send(make_key(self.data))
  
_counter = -1
_key_dict={}
data_file=None

def load_data():
    try:
        f = open('d:/data_file.txt','r',2048)
    except:
        f = None
    if f:
        last_key=''
        for line in f:
            v= eval(line)
            last_key=v[1]
            _key_dict[v[0]]=v[1]
            
        print 'last_key:%s' % last_key
        global _counter
        _counter = ascii_decrypt(last_key)
        f.close()

def make_key(raw_key):
    key=_key_dict.get(raw_key)
    if(not key):
        global _counter,data_file
        _counter = _counter + 1
        key = ascii_crypt(_counter)
        _key_dict[raw_key]=key
        data_file = open('d:/data_file.txt','a',1024)
        data_file.write(str([raw_key,key])+'\n')
        data_file.close()
    print raw_key,key
    return key

if __name__ == "__main__":
    load_data()
    make_key('asasdfdfszssasdfasdf')
    make_key('htasdfadszzssssasdfsfasdfdfasf')
    make_key('1234dfasszzasssdfdasdfadfasdsdzz')
    make_key('我asffsdfzzss是adfazz谁？？？')
    make_key('就adfasdaazzssdfsdff。。')
    make_key('15ss5aaszasdfdfassdf12345')

    
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

